const path = require('path');
const {join} = path;
const fs = require('fs');
const extract = require('extract-zip');

getFolderPath = function (filePath) {
    return path.dirname(filePath);
};

getParentFolderName = function (filePath) {
    let folderDir = path.dirname(filePath);
    folderDir = path.normalize(folderDir);
    folderDir = path.basename(folderDir);
    return folderDir;
};

getDirName = function (filePath) {
    return path.basename(filePath);
};

convertPath = function (filePath) {
    return path.resolve(filePath);
};
replacePath = function (filePath) {
    return filePath.replace(/\\/g, '/');
};
// 递归创建目录 同步方法
mkdirsSync = function (dirname) {
    try {
        if (fs.existsSync(dirname)) {
            return true;
        } else {
            if (mkdirsSync(path.dirname(dirname))) {
                fs.mkdirSync(dirname);
                return true;
            }
        }
    }catch (e){}
};
moveFile = function (file, movedFolder) {
    let fname = path.basename(file);
    fs.renameSync(file, path.join(movedFolder, fname));
};
getFileInfo = function (filePath) {
    const stat = fs.statSync(filePath);
    return {
        "size": stat.size,
        "name": path.basename(filePath),
    };
};

getFileObj = function (filePath) {
    return fs.createReadStream(filePath, {"encoding": "utf8"})
};

getAllFiles = function (folderPath) {
    if (!fileExists(folderPath)) return [];
    return fs.readdirSync(folderPath)
};
cantUploadFile = function (filename) {
    if (filename.indexOf(".") == 0) return true;
    let ext = filename.substring(filename.lastIndexOf(".")).toLowerCase();
    let exts = [".ts", ".m4s", ".m3u8", ".mp4", ".mp3", ".m4a", ".jpg", ".jpeg", ".png"];
    return exts.indexOf(ext) < 0;
};
/**
 *
 * @param path
 * @param max 最多获取几个文件
 * @param minSec 最少时间差 (秒)
 * @returns {[]}
 */
getFilesBySort = function (path, max = 10, minSec = 10) {
    if (max <= 0) return [];
    let result = [];

    let pathArray = fs.readdirSync(path);
    for (let i = 0; i < pathArray.length; i++) {
        let val = pathArray[i];
        if (this.cantUploadFile(val)) {
            continue;
        }
        let fPath = join(path, val);
        let stats = fs.statSync(fPath);
        if (stats.isFile()) {
            let lastChangeTime = stats.mtime;
            lastChangeTime = Date.parse(lastChangeTime);
            let disSec = (new Date().getTime() - lastChangeTime) / 1000;
            if (disSec >= minSec) {
                result.push(fPath);
                if (result.length >= max) {
                    break;
                }
            }
        }
    }
    return result;
};


getFileCount = function (path) {
    let count = 0;
    let pathArray = fs.readdirSync(path);
    for (let i = 0; i < pathArray.length; i++) {
        let val = pathArray[i];
        if (this.cantUploadFile(val)) {
            continue;
        }
        let fPath = join(path, val);
        let stats = fs.statSync(fPath);
        if (stats.isFile()) count++;
    }
    return count;
};

getChildFolders = function (folder_path) {
    let pathArray = fs.readdirSync(folder_path);
    let temp = [];
    for (let i = 0; i < pathArray.length; i++) {
        let val = pathArray[i];
        let fPath = join(folder_path, val);
        let stats = fs.statSync(fPath);
        if (stats.isDirectory) {
            temp.push(fPath);
        }
    }
    return temp;
};


function calcSizeSync(dirPath, cb) {
    let fileSize = 0;
    let error = null;
    if (!fileExists(dirPath)) {
        cb(false, fileSize);
        return;
    }

    function calc(dirPath, cb1) {
        const statObj = fs.statSync(dirPath);
        if (statObj.isDirectory()) {
            try {
                const files = fs.readdirSync(dirPath);
                let dirs = files.map(item => {
                    return path.join(dirPath, item)
                });
                for (let i = 0; i < dirs.length; i++) {
                    calc(dirs[i], cb1)
                }
            } catch (err) {
                error = err
            }
        } else {
            fileSize += statObj.size;
            cb1 && cb1()
        }
    }

    calc(dirPath);
    cb(error, fileSize)
}

function fileExists(file) {
    return fs.existsSync(file);
}

function deleteAllFiles(folder_path) {
    var files = [];
    if (fs.existsSync(folder_path)) {
        files = fs.readdirSync(folder_path);
        files.forEach(function (file, index) {
            var curPath = path.join(folder_path, file);
            let stat = fs.statSync(curPath);
            if (stat.isDirectory()) {
                deleteAllFiles(curPath);
            } else { // delete file
                fs.unlinkSync(curPath);
            }
        });
        // fs.rmdirSync(folder_path);
    }
}

readTxt = function (txt_path) {
    //调用readFile方法读取磁盘文件：异步操作
    let data = fs.readFileSync(txt_path)
    return data.toString();
};
writeText = function (url, str) {
    //同步的写入
    return fs.writeFileSync(url, str);
};

extractZip = function (zip_path, extract_folder, cb) {
    try {
        extract(zip_path, {dir: extract_folder}).then(function (err) {
            cb(false)
        });
    } catch (err) {
        console.log(err);
        cb(err);
    }
};

movieUploadedFolder = function (folder_path) {
    let uploaded = path.join(folder_path, "uploaded");
    let all = this.getAllFiles(uploaded);
    for (let i = 0; i < all.length; i++) {
        let f = path.join(uploaded, all[i]);
        this.moveFile(f, folder_path);
    }
};

deleteLogFiles = function (folder) {
    let count = 0;
    let pathArray = fs.readdirSync(folder);
    for (let i = 0; i < pathArray.length; i++) {
        let val = pathArray[i];
        if (val.indexOf(".log") > 0) {
            let curPath = path.join(folder, val);
            fs.unlinkSync(curPath);
        }
    }
    return count;
};
getFilePathInfo = function (filePath){
    let fileName = getFileInfo(filePath).name;
    let ext = path.extname(fileName).substr(1);
    let base = fileName.substring(0,fileName.lastIndexOf("."));
    const stat = fs.statSync(filePath);
    return {
        "folder": getFolderPath(filePath),
        "file_name": fileName,
        "base_name": base,
        "ext": ext,
        "size": stat.size,
    };
}
module.exports = {
    getFolderPath,
    convertPath,
    mkdirsSync,
    getFileInfo,
    getFileObj,
    getAllFiles,
    calcSizeSync,
    getParentFolderName,
    fileExists,
    deleteAllFiles,
    replacePath,
    moveFile,
    getFilesBySort,
    getFileCount,
    getDirName,
    getChildFolders,
    cantUploadFile,
    readTxt,
    writeText,
    extractZip,
    movieUploadedFolder,
    deleteLogFiles,
    getFilePathInfo,
};
